package com.tutu.cart.controller;

import com.tutu.cart.service.CartService;
import com.tutu.commons.checks.RemoveCartCheck;
import com.tutu.commons.checks.SaveCartCheck;
import com.tutu.commons.checks.UpdateCartCheck;
import com.tutu.commons.clients.ProductClient;
import com.tutu.commons.pojo.Cart;
import com.tutu.commons.utils.CollectError;
import com.tutu.commons.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Program: b2c-cloud-store
 * @Description:
 * @Author: JK.TuTu
 * @ @Version: 1.0
 * @Create: 2022-12-23 09:24
 **/
@Slf4j
@RestController
@RequestMapping("/cart")
@Api("用户购物车相关接口")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private ProductClient productClient;

    /**
     * 保存商品到购物车
     *
     * @param cart   用户id,商品Id
     * @param result 参数检验结果
     * @return R 返回结果实体对象
     */
    @PostMapping("/save")
    @ApiOperation("保存商品到购物车")
    public R save(@RequestBody @Validated(SaveCartCheck.class) Cart cart, BindingResult result) {
        if (result.hasErrors()) {
            String errorInfo = CollectError.getErrorInfo(result);
            return R.fail(errorInfo);
        }
        return cartService.saveCart(cart);
    }

    /**
     * 通过用户id获取购物车信息
     *
     * @param userId 用户id
     * @return 返回结果实体对象
     */
    @GetMapping("list/{userId}")
    @ApiOperation("通过用户id获取购物车信息")
    public R list(@PathVariable("userId") Integer userId) {
        List<Object> cartvos = cartService.getCartById(userId);
        return R.ok(cartvos);
    }


    /**
     * 更新购物车商品数量
     *
     * @param cart   购物车参数(用户id,商品id,更新过后的商品数量)
     * @param result 校验结果集
     * @return 返回结果实体对象
     */
    @PostMapping("update")
    @ApiOperation("更新购物车商量")
    public R update(@RequestBody @Validated(UpdateCartCheck.class) Cart cart, BindingResult result) {
        if (result.hasErrors()) {
            String errorInfo = CollectError.getErrorInfo(result);
            return R.fail(errorInfo);
        }
        return cartService.updateCart(cart);
    }


    /**
     * 删除购物车送数据
     *
     * @param cart   购物车参数(用户id,商品id)
     * @param result 检验结果集
     * @return 返回结果实体对象
     */
    @PostMapping("/remove")
    @ApiOperation("删除购物车数据")
    public R remove(@RequestBody @Validated(RemoveCartCheck.class) Cart cart, BindingResult result) {
        if (result.hasErrors()) {
            String errorInfo = CollectError.getErrorInfo(result);
            return R.fail(errorInfo);
        }
        return cartService.removeCart(cart) > 0 ? R.ok("删除购物车成功！") : R.fail("删除购物车失败!");
    }


}
